package com.kingzoon.seckill.service.impl.product;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.kingzoon.seckill.dao.SeckillDao;
import com.kingzoon.seckill.dao.SuccessKilledDao;
import com.kingzoon.seckill.dto.Exposer;
import com.kingzoon.seckill.dto.SeckillExecution;
import com.kingzoon.seckill.entity.Seckill;
import com.kingzoon.seckill.entity.SuccessKilled;
import com.kingzoon.seckill.service.SeckillService;

@Service
public class SeckillServiceImpl implements SeckillService {
	
	@Autowired
	private SeckillDao seckillDao;
	
	@Autowired
	private SuccessKilledDao successKilledDao;
	
	private final String slat = "#$$%^&*((HGTTTTYGGUJU776555554467878";

	public List<Seckill> getSeckillList() {
		// TODO Auto-generated method stub
		return seckillDao.queryAll(0, 4);
	}

	public Seckill getById(long seckillId) {
		// TODO Auto-generated method stub
		return seckillDao.queryById(seckillId);
	}

	public Exposer exportSeckillUrl(long seckillId) {
		Seckill seckill = seckillDao.queryById(seckillId);
		if(seckill == null){
			return new Exposer(false, seckillId);
		}
		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
		Date nowTime = new Date();
		if(nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()){
			return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
		}
		String md5 = getMD5(seckillId);
		//System.out.println("md5 =" + md5);
		return new Exposer(true, md5, seckillId);
	}
	
	private String getMD5(long seckillId){
		String base = seckillId + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

	@Transactional
	public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) {
		if(md5 == null || !md5.equals(getMD5(seckillId))){
			throw new RuntimeException();
		}
		
		Date nowTime = new Date();
		try {
			int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
			
			if(insertCount <= 0){
				throw new RuntimeException();
			}else{
				int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
				if(updateCount <= 0){
					throw new RuntimeException();
				}else{
					SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
					return new SeckillExecution(seckillId, 1, "秒杀成功！", successKilled);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

}
